package com.lancoo.znbkxx.teacher.aibkGenerateTestPaper.aibkGenerateDialog

import android.app.Dialog
import android.content.Context
import android.os.Bundle
import android.os.IBinder
import android.view.Gravity
import android.view.MotionEvent
import android.view.View
import android.view.ViewGroup
import android.view.inputmethod.InputMethodManager
import android.widget.EditText
import androidx.appcompat.app.AppCompatActivity
import com.lancoo.znbkxx.teacher.R
import com.lancoo.znbkxx.teacher.aibkTestCoach.networkRequest.entity.TypeThemeInfor
import com.lancoo.znbkxx.teacher.widget.MyLayoutManager
import kotlinx.android.synthetic.main.aibk_dialog_theme_type_choose.*


/*
* add by 王国龙
* 选择主题弹窗
* */
class DialogThemeTypeChoose(
        context: Context?,
        val activity: AppCompatActivity,
        val typeThemeInfor: TypeThemeInfor,
        var currentThemeName:String
) : Dialog(context!!, R.style.CustomDialog), View.OnClickListener {

    var oldThemeName = ""

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.aibk_dialog_theme_type_choose)
        window!!.setGravity(Gravity.BOTTOM) //设置弹窗右对齐
        window!!.setWindowAnimations(R.style.MyDialogBottomTranslate) //设置动画效果

        val wl = window!!.attributes
        //以下这两句是为了保证按钮可以水平满屏
        wl.width = ViewGroup.LayoutParams.MATCH_PARENT;
        wl.height = ViewGroup.LayoutParams.WRAP_CONTENT;
        onWindowAttributesChanged(wl)
        setCanceledOnTouchOutside(true)

        oldThemeName = currentThemeName

        //初始化界面数据
        setListViewData(initListView(""),currentThemeName)
        IvSearch.setOnClickListener(this)
        BtnSure.setOnClickListener(this)
    }

    /**
     * 初始化ListView
     */
    private fun initListView(searchTxt:String):MutableList<String> {
        var data: MutableList<String> = ArrayList() //ListView数据源
        val size = typeThemeInfor.size
        //初始化字符数组
        for (i in 0 until size) {
            val chineseName = typeThemeInfor[i].ChineseName
            if(searchTxt.isEmpty()){
                data.add(chineseName)
            }else {
                if (chineseName.contains(searchTxt)) {
                    data.add(chineseName)
                }
            }
        }
        return data
    }

    /**
     * 设置ListView的内容
     */
    private fun setListViewData(dataList: MutableList<String>,themeName:String) {
        //显示题型选择区域
        val layout = MyLayoutManager()
        layout.isAutoMeasureEnabled = true //必须，防止recyclerview高度为wrap时测量item高度0
        RvThemeTypeChoose.layoutManager = layout
        val adapterThemeType = AibkThemeTypeAdapter(activity, dataList,themeName)
        adapterThemeType.setClickDialogListener(object :AibkThemeTypeAdapter.OnClickQuesTypeListener{
            override fun onClickThemeType(themeName: String) {
                currentThemeName = themeName
                adapterThemeType.notifyDataSetChanged()
            }
        })
        RvThemeTypeChoose.adapter = adapterThemeType
    }

    private var clickThemeListener: OnClickThemeListener? = null

    /*
   * 设置答题卡题号点击事件
   * */
    interface OnClickThemeListener {
        fun onClickSure(themType:String)//确认
    }

    fun setClickThemeListener(clickThemeListener: OnClickThemeListener?) {
        this.clickThemeListener = clickThemeListener
    }

    override fun onClick(v: View?) {
        when(v?.id){
            R.id.IvSearch ->{
                val searchTxt = EdtSearch.text.toString()
                setListViewData(initListView(searchTxt),oldThemeName)
            }
            R.id.BtnSure ->{
                clickThemeListener!!.onClickSure(currentThemeName)
                dismiss()
            }
        }
    }


    /**************************************************************************/
    /*
    * 软键盘点击空白处自动回收，好用
    * */
    //时间分发方法重写
    override fun dispatchTouchEvent(ev: MotionEvent): Boolean {
        //如果是点击事件，获取点击的view，并判断是否要收起键盘
        if (ev.getAction() === MotionEvent.ACTION_DOWN) {
            //获取目前得到焦点的view
            val v = currentFocus
            //判断是否要收起并进行处理
            if (isShouldHideKeyboard(v, ev)) {
                hideKeyboard(v!!.windowToken)
            }
        }
        //这个是activity的事件分发，一定要有，不然就不会有任何的点击事件了
        return super.dispatchTouchEvent(ev)
    }

    //判断是否要收起键盘
    private fun isShouldHideKeyboard(v: View?, event: MotionEvent): Boolean {
        //如果目前得到焦点的这个view是editText的话进行判断点击的位置
        if (v is EditText) {
            val l = intArrayOf(0, 0)
            v!!.getLocationInWindow(l)
            val left = l[0]
            val top = l[1]
            val bottom = top + v.height
            val right = left + v.width
            // 点击EditText的事件，忽略它。
            return (event.getX() <= left || event.getX() >= right
                    || event.getY() <= top || event.getY() >= bottom)
        }
        // 如果焦点不是EditText则忽略，这个发生在视图刚绘制完，第一个焦点不在EditText上
        return false
    }

    //隐藏软键盘并让editText失去焦点
    private fun hideKeyboard(token: IBinder?) {
        EdtSearch.clearFocus()
        if (token != null) {
            //这里先获取InputMethodManager再调用他的方法来关闭软键盘
            //InputMethodManager就是一个管理窗口输入的manager
            val im: InputMethodManager = activity.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
            if (im != null) {
                im.hideSoftInputFromWindow(token, InputMethodManager.HIDE_NOT_ALWAYS)
            }
        }
    }
    /**************************************************************************/

}